import axios from "axios";
import {Message} from "element-ui";
import router from "./router"

// 1、添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  async config => {
    config.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      'X-Requested-With': 'XMLHttpRequest',
      'Access-Control-Allow-Origin': '*'
    }
    if (localStorage.getItem('Authorization')) {
      config.headers.Authorization = localStorage.getItem('Authorization');
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  });

// 2、响应拦截器
axios.interceptors.response.use(success => {
  if (success.status && success.status === 200) {
    if (success.data.success === false) {
      judge(success.code);
    }
    if (success.data.success === true && success.data.message !== '') {
      Message.success(success.data.message);
    }
    return success;
  }
}, error => {
  let code = 0;
  if (error.response !== undefined) {
    code = error.response.status;
  }
  judge(code);
  return error.response;
});

// 根据http状态码提示消息，跳转页面
function judge(code){
  let r = null;
  let msg = '';
  switch (code) {
    case 400:
      msg = '请求错误！'
      break;
    case 401:
      localStorage.removeItem('Authorization');
      msg = '未授权，请重新登录'
      r = '/login';
      break;
    case 403:
      msg = '拒绝访问'
      break;
    case 404:
      msg = '请求错误,未找到该资源'
      // window.location.href = "/NotFound"
      break;
    case 405:
      msg = '请求方法未允许'
      break;
    case 408:
      msg = '请求超时'
      break;
    case 500:
      if (error.response.data.message !== null) {
        msg = error.response.data.message;
      } else
        msg = '服务器出错!'
      break;
    case 501:
      msg = '服务器无法识别请求方法'
      break;
    case 502:
      msg = '网络错误'
      break;
    case 503:
      msg = '服务不可用'
      break;
    case 504:
      msg = '网络超时'
      break;
    case 505:
      msg = 'http版本不支持该请求'
      break;
    default:
      msg = '未登录或者登录过期，请重新登录！'
      r = '/login';
  }
  // 在某些特定情况下跳转页面
  if (r !== null) {
    localStorage.clear();
    router.replace(r).then(r => {
    });
  }
  Message.error({message: msg});
}

/**
 * 封装请求
 */
let base = '/api';
export const postApi = (url, params, hed) => {
  return axios({
    header: hed,
    method: 'post',
    url: `${base}${url}`,
    data: params
  });
};

// get请求
export const getApi = (url, params, hed) => {
  return axios({
    header: hed,
    method: 'get',
    url: `${base}${url}`,
    data: params
  });
};

// put请求
export const putApi = (url, params) => {
  return axios({
    method: 'put',
    url: `${base}${url}`,
    data: params
  });
};

// delete请求
export const deleteApi = (url, params) => {
  return axios({
    method: 'delete',
    url: `${base}${url}`,
    data: params
  });
};
